var $parent = $(mod.element);

var fetch = function (callback) {
    processAfterTrust(function(uid){
        lib.api({
            method: 'beibei.h5.lifecycle.recoms.get',
            type: 'GET',
            dataType: 'json',
            data: 'recom_type=2',
            error: function () {
                lib.popup.alert('网络繁忙，请稍后再试！');  
            },
            success: function (data) { 

                callback(data);
            }
        });
    }, true);
};

var processData = function (data) {
    //数据进一步加工
    var process = function (obj, isHight) {
        if (obj) {
            obj.forEach(function (val, index) {
                val.price = (parseInt(val.price)/100).toFixed(1);
                val.origin_price = '¥' + (parseInt(val.origin_price)/100).toFixed(0);
                val.discount = (parseInt(val.price)/10).toFixed(1);
                //val.img += '!320x320.jpg';
       l         isHight ? val.boxNum = index : val.boxNum = ((+index) + 1000);
            });
        }
    }
    process(data.rule_list, true);
    process(data.mine_list, false);
    return data;
};

var render = function(newData) {
    
    var renderedRule = mod.render(mod.tmpl.subTemplate, {
        items: newData.rule_list
    });
    $parent.find('.recommend-high').append(renderedRule);
    
    var renderedMine = mod.render(mod.tmpl.subTemplate, {
        items: newData.mine_list
    });
    $parent.find('.recommend-low').append(renderedMine);
};

var handle = function () {
    var $box = $parent.find('.J_recommend-box');
    
    $box.on('click', function() {
        var type = $(this).data('type'),
            iid = $(this).data('iid'),
            boxNum = $(this).data('boxnum'),
            href = '';
            //console.log(boxNum);
        switch (type) {
            case 1:
            case 51:
                href = 'http://m.beibei.com/detail/detail.html?iid=' + iid +'&beibeiapp_info={"target":"detail","iid":' + iid + '}';
                break;
            case 2:
                href = 'http://m.beibei.com/tuan/tuan-detail.html?iid=' + iid + '&beibeiapp_info={"target":"detail","iid":' + iid + '}';
                break;
            case 3:
            case 53:
                href = 'http://m.beibei.com/oversea/oversea-detail.html?iid=' + iid + '&beibeiapp_info={"target":"detail","iid":' + iid + '}';
                break;
            default:
        }
        
        lib.statisticsTool.sendLog({
            et: 'click',
            entity_type: 'shopping_push_box',
            json: {
                type: 'tab',
                boxNum: boxNum
            }
        });
        
        window.location.href = href;
    });
    
};

mod.ready(function(){
    
    fetch(function (resp) {
        render(processData(resp));
        lib.lazyload().getLazyImg();
        handle();
    });
    
});
